<!--
 * @Description: 发起签约/签约详情
 * @Author: 龙春雨
 * @Date: 2023-04-14 10:05:04
-->
<template>
  <el-dialog
    :title="title"
    :visible.sync="_visible"
    width="1000px"
    append-to-body
  >
    <div>签约类型：领养协议</div>
    <avue-form
      ref="addForm"
      v-model="form"
      :option="formOption"
      @submit="submitForm"
    >
      <template #petId="{disabled}">
        <el-select
          v-if="!disabled"
          v-model="form.petId"
          filterable
          placeholder="请选择"
          @change="changeId"
        >
          <el-option
            v-for="item in codeList"
            :key="item.code"
            :label="item.code"
            :value="item.id"
          >
            <template>
              <div
                class="sb"
                style="padding: 0 20px"
              >
                <span>{{ item.nickName }}</span>
                <span>{{ item.code }}</span>
              </div>
            </template>
          </el-option>
        </el-select>
        <div v-else>
          {{ form.petCode }}
        </div>
      </template>
      <template #phone>
        <el-select
          v-model="form.phone"
          filterable
          clearable
          :disabled="formType === 'check'"
          remote
          placeholder="请选择"
          :remote-method="remoteMethod"
          @change="changPhone"
        >
          <el-option
            v-for="item in phoneList"
            :key="item.userId"
            :label="item.phone"
            :value="item.phone"
          >
            <template>
              <div
                class="sb"
                style="padding: 0 20px"
              >
                <span>{{ item.nickname }}</span>
                <span>{{ item.phone }}</span>
              </div>
            </template>
          </el-option>
        </el-select>
      </template>
    </avue-form>
    <span
      slot="footer"
      class="dialog-footer"
    >
      <el-button @click="_visible = false">取 消</el-button>
      <el-button
        v-if="formType !== 'check'"
        :loading="loading"
        type="primary"
        @click="submitForm"
      >
        确 定
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import { formOption } from '@/const/crud/pet/contractMng';
import { getPetListByBaseId, getPhoneList, addObj } from '@/api/core/agreement';
import { mapGetters } from 'vuex';
import { RESERVE_AGGREE } from '@/const/type';
export default {
  name: 'AddDialog',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    agreementDetail: {
      type: Object,
      default: () => {},
    },
    agreeList: {
      type: Array,
    },
  },
  data() {
    return {
      form: {},
      codeList: [],
      phoneList: [],
      loading: false,
      petId: '',
      RESERVE_AGGREE,
    };
  },
  computed: {
    _visible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit('update:visible', val);
      },
    },
    ...mapGetters(['userInfo']),
    formType() {
      return this.agreementDetail.formType;
    },
    formOption() {
      if (this.formType === 'add') {
        return formOption(false);
      } else {
        return formOption(true);
      }
    },
    title() {
      if (this.formType === 'add') {
        return '发起领养协议';
      } else {
        return '查看领养协议';
      }
    },
    detail() {
      return this.agreementDetail.detail;
    },
  },
  watch: {
    detail(val) {
      if (val) {
        this.form = this.detail;
      }
    },
    _visible(val) {
      if (!val) {
        this.$refs['addForm'].resetFields();
        this.form.petTypeName = '';
      } else {
        this.getPetList();
        this.getUserPhoneList();
      }
    },
  },
  mounted() {
    // this.getPetList();
    // this.getUserPhoneList();
  },
  methods: {
    submitForm() {
      this.$refs.addForm.validate(async (valid, done) => {
        if (valid) {
          this.loading = true;
          const params = {
            agreementPetInfoBOList: [
              {
                baseId: this.form.baseId,
                petId: this.petId,
              },
            ],
            userId: this.form.userId,
            adoptAddress: this.form.adoptAddress,
            type: RESERVE_AGGREE.ADOPT,
          };
          addObj(params)
            .then((res) => {
              if (!res.data) return;
              this.$emit('refreshList');
              this._visible = false;
              this.loading = false;
              this.$message.success('操作成功！');
              done();
            })
            .catch((err) => {
              this.loading = false;
              done();
              throw new Error(err);
            });
        }
      });
    },
    async getPetList() {
      const res = await getPetListByBaseId();
      this.codeList = res.data.data;
    },
    remoteMethod(phone) {
      if (phone !== '' && phone.length > 1) {
        setTimeout(() => {
          this.getUserPhoneList({ phone });
        }, 50);
      } else {
        this.phoneList = [];
      }
    },
    async getUserPhoneList(params) {
      this.phoneList = [];
      const res = await getPhoneList({
        ...params,
        type: '1',
        adoptFlag: '1',
      });
      this.phoneList = res.data.data;
    },
    changPhone(val) {
      console.log('cc', val);
      const data = this.phoneList.find((item) => {
        return item.phone === val;
      });
      this.form.userId = data.userId;
      this.form.nickName = data.nickname;
      this.form.adoptName = data.name;
      this.form.adoptCard = data.idCard;
    },
    changeId(val) {
      const data = this.codeList.find((item) => {
        return item.id === val;
      });
      this.form.petName = data.nickName;
      this.form.petTypeName = `${data.typeName}｜${data.varietyName}`;
      this.form.petSex = data.gender;
      this.form.baseId = data.baseId;
      this.petId = data.id;
      this.form.baseName = data.baseName;
      this.form.baseAddress = data.baseAddress;
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
